//
//  CampusDetailViewController.m
//  ShowYork
//
//  Created by hxh on 2021/3/26.
//  Copyright © 2021 hxh. All rights reserved.
//

#import "CampusDetailViewController.h"
#import "CampusPreviewPicBroswerViewController.h"
#import "CampusVideoPlayerViewController.h"
#import "CampusPreviewPicListViewController.h"
#import "CampusPostQuestionViewController.h"
#import "CampusQuestionDetailViewController.h"
#import "CampusVlogDetailViewController.h"
#import "CampusDetailVideoPreviewCell.h"
#import "CommonWebViewController.h"
#import "CampusPreviewVideoListViewController.h"
#import "CampusPreviewPicListViewController.h"
#import "CampusPreviewQuesionListController.h"
#import "CampusPicBroswerViewController.h"
#import "CampusDetailHeaderCell.h"
#import "CampusDetailPreviewViewCell.h"
#import "CampusDetailLinkCell.h"
#import "CampusDetailVideoPreviewCell.h"
#import "CampusDetailImagePreviewCell.h"
#import "CampusQuestionAddCell.h"
#import "CampusQuetionItemCell.h"
#import "CampusDetailTitleView.h"
#import "RPAppShareView.h"
#import "CampusQuestionDetailModel.h"
#import "CampusSchoolDetailModel.h"
#import "CampusSchoolPictureItemModel.h"

@interface CampusDetailViewController ()<UITableViewDelegate,UITableViewDataSource,CampusDetailVideoPreviewCellDelegate,CampusDetailImagePreviewCellDelegate,CampusDetailLinkCellDelegate,CampusQuetionItemCellDelelgate,CampusQuestionAddCellDelegate,CampusDetailPreviewViewCellDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)CampusSchoolDetailModel *itemModel;
@end

@implementation CampusDetailViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = NO;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self loadDataSource];
    [self registNote];
}

- (void)setUI{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"campus_share_tag"] style:UIBarButtonItemStyleDone target:self action:@selector(shareMethod)];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.estimatedRowHeight = 100.0f;
    self.tableView.estimatedSectionHeaderHeight = .0f;
    self.tableView.estimatedSectionFooterHeight = .0f;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 44)];
    footerView.backgroundColor = [UIColor whiteColor];
    
    self.tableView.tableFooterView = footerView;
    
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

    }];
    
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.hidden = YES;
    footer.cl_height = 138.0f;
    [footer endRefreshingWithNoMoreData];
    
    self.tableView.mj_footer = footer;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
}

- (void)loadDataSource{
    [self showDataLoadState];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = self.schId;
    param[@"md5"] = [RPAppManager md5StrWithApi:SchoolDetail];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(SchoolDetail) parames:param success:^(id responseObj) {
    
        [self hideDataLoadLoadState];
        
        self.tableView.mj_footer.hidden = NO;
        
        self.itemModel = [CampusSchoolDetailModel mj_objectWithKeyValues:responseObj[RESPONSE]];
    
        [self.tableView reloadData];
   
    } failure:^(NSError *error) {
        [self hideDataLoadLoadState];
        [WHToast showErrorWithMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}
- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateQuestionList:) name:@"updateQuestionList" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDetailQuestionAnswerCount:) name:@"updateDetailQuestionAnswerCount" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateQuestionTime:) name:@"updateQuestionTime" object:nil];
}
- (void)updateDetailQuestionAnswerCount:(NSNotification *)note{
    NSNumber *questionId = note.userInfo[@"data"];
    BOOL isAdd = [note.userInfo[@"status"] boolValue];
    
    [self.itemModel.askList enumerateObjectsUsingBlock:^(CampusSchoolQuestionItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.id isEqualToNumber:questionId]) {
            int askCount = obj.answerCount.intValue;
            askCount = askCount + (isAdd?(1):(-1));
            obj.answerCount = @(askCount);
            *stop = YES;
        }
    }];
    [self.tableView reloadData];
}

- (void)updateQuestionTime:(NSNotification *)note{
    NSNumber *questionId = note.userInfo[@"data"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = questionId;
    param[@"md5"] = [RPAppManager md5StrWithApi:SchoolQuestionDetail];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(SchoolQuestionDetail) parames:param success:^(id responseObj) {

        CampusQuestionDetailModel *questionModel = [CampusQuestionDetailModel mj_objectWithKeyValues:responseObj[RESPONSE]];
        __block BOOL isUpdate = NO;
        [self.itemModel.askList enumerateObjectsUsingBlock:^(CampusSchoolQuestionItemModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.id isEqualToNumber:questionModel.id]) {
                obj.createTime = questionModel.createTime;
                isUpdate = YES;
                *stop = YES;
            }
        }];
        
        if (isUpdate) {
            [self.tableView reloadSection:3 withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        

    } failure:^(id error) {
        
    }];
}

- (void)updateQuestionList:(NSNotification *)note{
    CampusQuestionDetailModel *model = note.userInfo[@"data"];
    
    CampusSchoolQuestionItemModel *itemModel = [[CampusSchoolQuestionItemModel alloc]init];
    itemModel.id = model.id;
    itemModel.answerCount = @0;
    itemModel.createTime = model.createTime;
    itemModel.question = model.question;
    
    NSMutableArray *askList = [NSMutableArray arrayWithArray:self.itemModel.askList];
    
    [askList insertObject:itemModel atIndex:0];

    self.itemModel.askList = askList;
    
    self.itemModel.askCount = @(askList.count);

    [self.tableView reloadData];
    
}

- (void)shareMethod{
    
    if ([RPAppManager isShowNetworkView]) {
        [WHToast showErrorWithMessage:@"网络好像有点问题，请检查后重试" duration:2 finishHandler:nil];
        return;
    }
    [RPAppShareView showCompleteblock:^(XHShareViewPlatformType platformType) {
        UMSocialPlatformType type = UMSocialPlatformType_UnKnown;
        switch (platformType) {
            case XHShareViewPlatformTypeWeChatSession:
                type = UMSocialPlatformType_WechatSession;
                break;
            case XHShareViewPlatformTypeWeChatMoments:
                type = UMSocialPlatformType_WechatTimeLine;
                break;
            case XHShareViewPlatformTypeQQ:
                type = UMSocialPlatformType_QQ;
                break;

            case XHShareViewPlatformTypeQQZone:
                type = UMSocialPlatformType_Qzone;
                break;

            case XHShareViewPlatformTypeQQWeibo:
                type = UMSocialPlatformType_Sina;
                break;
            default:
                break;
        }
        if (![[UMSocialManager defaultManager] isInstall:type]) {
            if (type == UMSocialPlatformType_WechatSession || type == UMSocialPlatformType_WechatTimeLine) {
                [WHToast showMessage:@"请先安装微信" duration:2 finishHandler:nil];
            }
            if (type == UMSocialPlatformType_QQ || type == UMSocialPlatformType_Qzone) {
                [WHToast showMessage:@"请先安装QQ" duration:2 finishHandler:nil];
            }
            if (type == UMSocialPlatformType_Sina) {
                [WHToast showMessage:@"请先安装微博" duration:2 finishHandler:nil];
            }
            return;
        }
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];

        NSString *title = self.itemModel.school.name;

        //创建网页内容对象
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:@"" thumImage:self.itemModel.school.logo];
        //设置网页地址
        shareObject.webpageUrl = [NSString stringWithFormat:@"%@school/intro?schoolId=%@",HtmlUrl,self.itemModel.school.id];
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:type messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }else{

            }
        }];
    }];
}
- (void)updateShareCountSource{
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.itemModel == nil) {
        return 0;
    }
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 3;
    }
    if (section == 1) {
        return self.itemModel.vlogList.count == 0?0:1;
    }
    if (section == 2) {
        return self.itemModel.pictureList.count == 0?0:1;
    }
    if (section == 3) {
        return self.itemModel.askList.count == 0?1:self.itemModel.askList.count;
    }
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            CampusDetailHeaderCell *cell = [CampusDetailHeaderCell cellWithTableView:tableView];
            [cell setModel:self.itemModel.school];
            return cell;
        }else if (indexPath.row == 1){
            CampusDetailPreviewViewCell *cell = [CampusDetailPreviewViewCell cellWithTableView:tableView];
            [cell setItemModel:self.itemModel.school];
            cell.delegate = self;
            return cell;
        }else{
            CampusDetailLinkCell *cell = [CampusDetailLinkCell cellWithTableView:tableView];
            cell.delegate = self;
            return cell;
        }
    }
    if (indexPath.section == 1) {
        CampusDetailVideoPreviewCell *cell = [CampusDetailVideoPreviewCell cellWithTableView:tableView];
        [cell setVlogList:self.itemModel.vlogList];
        cell.delegate = self;
        return cell;
    }
    if (indexPath.section == 2) {
        CampusDetailImagePreviewCell *cell = [CampusDetailImagePreviewCell cellWithTableView:tableView];
        [cell setPictureList:self.itemModel.pictureList maxCount:self.itemModel.pictureCount];
        cell.delegate = self;
        return cell;
    }
    if (indexPath.section == 3) {
        if (self.itemModel.askList.count == 0) {
            CampusQuestionAddCell *cell = [CampusQuestionAddCell cellWithTableView:tableView];
            cell.delegate = self;
            return cell;
        }
        CampusQuetionItemCell *cell = [CampusQuetionItemCell cellWithTableView:tableView];
        [cell setItemModel:self.itemModel.askList[indexPath.item]];
        cell.delegate = self;
        return cell;
    }
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.01f;
    }
    if (section == 1) {
        return self.itemModel.vlogList.count == 0?0.01f:52.0f;
    }
    if (section == 2) {
        return self.itemModel.pictureList.count == 0?0.01f:52.0f;
    }
    return 52.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    __weak typeof(self)weakSelf = self;
    if (section == 1 && self.itemModel.vlogList.count > 0) {
        CampusDetailTitleView *titleView = [[CampusDetailTitleView alloc]initWithTitle:@"校园Vlog" completeBlock:^{
            CampusPreviewVideoListViewController *vc = [[CampusPreviewVideoListViewController alloc]init];
            vc.schId = weakSelf.itemModel.school.id;
            vc.schoolName = weakSelf.itemModel.school.name;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }];
        titleView.showMore = self.itemModel.vlogCount.intValue > 4;
        return titleView;
    }
    if (section == 2 && self.itemModel.pictureList.count > 0) {
        CampusDetailTitleView *titleView = [[CampusDetailTitleView alloc]initWithTitle:@"校园图集" completeBlock:^{
            CampusPreviewPicListViewController *vc = [[CampusPreviewPicListViewController alloc]init];
            vc.schId = weakSelf.itemModel.school.id;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }];
        titleView.showMore = self.itemModel.pictureCount.intValue > 5;
        return titleView;
    }
    if (section == 3) {
        CampusDetailTitleView *titleView = [[CampusDetailTitleView alloc]initWithTitle:@"问一问" completeBlock:^{
            CampusPreviewQuesionListController *vc = [[CampusPreviewQuesionListController alloc]init];
            vc.schId = weakSelf.itemModel.school.id;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }];
        titleView.showMore = self.itemModel.askCount.intValue > 0;
        return titleView;
    }

    return nil;
  
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

#pragma mark - CampusDetailLinkCellDelegate
-(void)didSelectedLinkByTag:(NSInteger)tag{
    CommonWebViewController *webVC = [[CommonWebViewController alloc]init];
    webVC.isDark = NO;
    if (tag == 0) {
        webVC.webUrl = self.itemModel.school.websiteUrl;
    }
    if (tag == 1) {
        webVC.webUrl = self.itemModel.school.recruitUrl;
    }
    [self.navigationController pushViewController:webVC animated:YES];
}

#pragma mark - CampusDetailVideoPreviewCell
- (void)playSchoolVlogByItem:(CampusSchoolVideoItemModel *)vlogItem{
    
    [self showDataLoadState];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:SchoolVlogList];
    param[@"pageIndex"] = @(1);
    param[@"pageSize"] = @(10);
    param[@"id"] = self.schId;
    param[@"usrId"] = [RPAppManager getCustomerId];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(SchoolVlogList) parames:param success:^(id responseObj) {
        [self hideDataLoadLoadState];
        NSArray *result =  [CampusSchoolVideoItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
        
        __block NSInteger index = -1;
        
        [result enumerateObjectsUsingBlock:^(CampusSchoolVideoItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.id isEqualToNumber:vlogItem.id]) {
                index = idx;
                *stop = YES;
            }
        }];
        if (index != -1) {
            
            [MobClick event:@"show_vlog_detail"];
            
            NSMutableDictionary *res = [NSMutableDictionary dictionary];
            res[@"currentIndex"] = @(index);
            res[@"currentPage"] = @(1);
            res[@"listSource"] = result;
            res[@"lastPage"] = @([responseObj[RESPONSE][LASTPAGE]boolValue]);
            res[@"schoolId"] = self.itemModel.school.id;
            res[@"schoolName"] = self.itemModel.school.name;
            CampusVlogDetailViewController *vc = [[CampusVlogDetailViewController alloc]initWithConfigInfo:res];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            [WHToast showErrorWithMessage:@"该视频不存在" duration:2 finishHandler:nil];
        }

    } failure:^(id error) {
        [self hideDataLoadLoadState];
    }];
}
#pragma mark -  CampusDetailPreviewViewCellDelegate
- (void)showPreviewPicture{
    
    if (self.itemModel.school.advertisement.length == 0) {
        return;
    }
    CampusPreviewPicBroswerViewController *vc = [[CampusPreviewPicBroswerViewController alloc]initWithPreviewUrl:self.itemModel.school.advertisement];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)showPreviewVideo{
    
    CampusVideoPlayerViewController *vc = [[CampusVideoPlayerViewController alloc]init];
    vc.videoUrl = self.itemModel.school.advertisement;
    
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
}
#pragma mark - CampusQuetionItemCellDelelgate
- (void)showQuestionDetail:(CampusSchoolQuestionItemModel *)itemModel{
    
    [self showDataLoadState];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = itemModel.id;
    param[@"md5"] = [RPAppManager md5StrWithApi:SchoolQuestionDetail];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(SchoolQuestionDetail) parames:param success:^(id responseObj) {
        
        [self hideDataLoadLoadState];

        CampusQuestionDetailViewController *vc = [[CampusQuestionDetailViewController alloc]init];
        vc.questionId = itemModel.id;
        [self.navigationController pushViewController:vc animated:YES];
        
    } failure:^(NSError *error) {
        [self hideDataLoadLoadState];
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}
#pragma mark - CampusQuestionAddCellDelegate
- (void)addQuestion{
    
    [self.view endEditing:YES];
    
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    
    CampusPostQuestionViewController *vc = [[CampusPostQuestionViewController alloc]init];
    vc.schId = self.schId;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - CampusDetailImagePreviewCellDelegate
- (void)showMorePicture{
    CampusPreviewPicListViewController *vc = [[CampusPreviewPicListViewController alloc]init];
    vc.schId = self.schId;
    [self.navigationController pushViewController:vc animated:YES];

}
- (void)showTargetPictureAtIndex:(NSInteger)index{
  
    [self showDataLoadState];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:SchoolPictureList];
    param[@"pageIndex"] = @(1);
    param[@"pageSize"] = @(10);
    param[@"id"] = self.schId;
    param[@"usrId"] = [RPAppManager getCustomerId];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(SchoolPictureList) parames:param success:^(id responseObj) {
        [self hideDataLoadLoadState];

        NSArray *result =  [CampusSchoolPictureItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];

        [MobClick event:@"show_pic_detail"];
        NSMutableDictionary *res = [NSMutableDictionary dictionary];
        res[@"currentIndex"] = @(index);
        res[@"currentPage"] = @(1);
        res[@"listSource"] = result;
        res[@"total"] = responseObj[RESPONSE][TOTAL];
        res[@"schId"] = self.schId;
        res[@"lastPage"] = @([responseObj[RESPONSE][LASTPAGE]boolValue]);
        CampusPicBroswerViewController *vc = [[CampusPicBroswerViewController alloc]initWithConfigInfo:res];
        [self.navigationController pushViewController:vc animated:YES];
        
    } failure:^(id error) {
        [self hideDataLoadLoadState];
    }];
}


@end
